
package com.songcy.servlet;

import java.io.*;
import java.util.List;

import javax.servlet.*;
import javax.servlet.http.*;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class FileUploadServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {
		this.doPost(request, response);
	}

	@SuppressWarnings("unchecked")
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {
		
		String arg = request.getParameter("arg");
		String img1 = request.getParameter("img1");
		String img2 = request.getParameter("img2");
		System.out.println("img1 "+img1 +" img2 "+img2);
		String radio = null;
		String filename = null;
		// 采用apache工具包进行文件上传操作
		DiskFileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);
		try {
			List<FileItem> fileitems = upload.parseRequest(request);
			for (FileItem item : fileitems) {
				if (item.isFormField()) {
					String name = item.getFieldName();
					String value = item.getString();
					
					// 转换下字符集编码
					value = new String(value.getBytes("iso-8859-1"), "utf-8");
					System.out.println(name + "=" + value);
				} else {
					double rand = (Math.random());
					filename =rand+item.getName();
					//System.out.println(filename);
					ServletContext context = getServletContext();
					
					// 上传的文件存放路径为...\\WebRoot\\upload\\filename
					String dir = context.getRealPath("upload");
					File file = new File(dir, filename);
					file.createNewFile();
					
					// 获得流，读取数据写入文件
					InputStream in = item.getInputStream();
					FileOutputStream fos = new FileOutputStream(file);
					
					int len;
					byte[] buffer = new byte[1024];
					while ((len = in.read(buffer)) > 0)
						fos.write(buffer, 0, len);
					// 关闭资源文件操作
					fos.close();
					in.close();
					// 删除临时文件
					item.delete();
					if(arg.equals("1"))
					{
						request.setAttribute("img1", filename);
						request.setAttribute("img2", img2);
					}
					else if(arg.equals("2"))
					{
						request.setAttribute("img2", filename);
						request.setAttribute("img1", img1);
					}
					request.getRequestDispatcher("scypage/addcart.jsp").forward(request, response);
					System.out.println(" file upload ok");
					
					
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}